var express = require('express');
var router = express.Router();
var md5=require("md5");
var db = require('../../../libs/mysql');
//统一返回格式
var res_Data;
router.use( function(req, res, next) {
    res_Data = {
        code: 0,
        message: ''
    }
    next();
});

router.get('/',function (req,res) {
    res.render('web/user/reg');
})
router.post('/',function (req,res) {
    var nickname = req.body.nickname,
        password = req.body.password,
        repassword = req.body.repassword;
    function numYD(from , to) {

        var Num = Math.ceil(Math.random()*(to-from))+from;

        return Num;
    }
    var YD = numYD(111111,999999);

    if(nickname == '' || nickname.length < 2 || nickname.length > 12){
        res_Data.code = 1;
        res_Data.message = '用户名长度为2到12之间。';
        res.json(res_Data);
        return;
    }
    if(password == '' || password < 6 || password > 16){
        res_Data.code = 2;
        res_Data.message = '密码长度为6到16之间。';
        res.json(res_Data);
        return;
    }
    if(password != repassword){
        res_Data.code = 3;
        res_Data.message = '密码2次输入不相同。';
        res.json(res_Data);
        return;
    }

    password = md5(md5('123456'+'yindume')+'node+mysql'+password+'exit;');
    db.query(`SELECT 1 FROM user WHERE YD='${YD}' limit 1`,(err,data) => {
        if(err){
            res.status(500).send('注册判断yd').end();
        }else {
            if(data[0]){
                res_Data.code = 4;
                res_Data.message = '系统自动生成的YD已存在，请重新注册。';
                res.json(res_Data);
                return;
            }else {
                db.query(`INSERT INTO user ( YD, nickname, password )
                       VALUES
                       ( ${YD}, '${nickname}','${password}' );`,(err,data)=>{
                    if(err){
                        res.status(500).send('注册数据插入数据库失败').end();
                    }else {
                        db.query(`SELECT * FROM user WHERE id = '${data.insertId}'`,(err,data)=>{
                            res_Data.message = '注册成功';
                            res_Data.userInfo = {
                                id: data[0].id,
                                YD : data[0].YD,
                                nickname : escape(data[0].nickname),
                                isAdmin: data[0].isAdmin
                            };
                            req.cookies.set('userInfo', JSON.stringify(res_Data.userInfo));
                            res.json(res_Data);
                            return;
                        });
                    }
                })
            }

        }
    });


})
module.exports = router;